<?php
/**
 * tpshop
 * ============================================================================
 * 版权所有 2015-2027 深圳搜豹网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.tp-shop.cn
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * Author: 当燃
 * Date: 2015-09-09
 */
namespace Seller\Controller;
use Seller\Logic\OrderLogic;
use Think\AjaxPage;
use Think\Page;
class OrderController extends BaseController {
    public  $order_status;
    public  $shipping_status;
    public  $pay_status;
    /*
     * 初始化操作
     */
    public function _initialize() {
        parent::_initialize();
        C('TOKEN_ON',false); // 关闭表单令牌验证
        // 订单 支付 发货状态
        $this->order_status = C('ORDER_STATUS');
        $this->pay_status = C('PAY_STATUS');
        $this->shipping_status = C('SHIPPING_STATUS');
        $this->assign('order_status',$this->order_status);
        $this->assign('pay_status',$this->pay_status);
        $this->assign('shipping_status',$this->shipping_status);
    }

    /*
     *订单首页
     */
    public function index(){
    	$begin = date('Y/m/d');//30天前
        //$begin = date('Y/m/d',time());//30天前 //
    	$end = date('Y/m/d',time());
        $goods_class=M('goods_category')->where("level=3")->select(); 	
        $this->assign('goods_class',$goods_class);
    	$this->assign('timegap',$begin.'-'.$end);
        $this->display();
    }

    /*
     *Ajax首页
     */
    public function ajaxindex(){

        $orderLogic = new OrderLogic();       
        $timegap = I('timegap');
        if($timegap){
        	$gap = explode('-', $timegap);
        	$begin = strtotime($gap[0]);
        	$end = strtotime($gap[1])+86399;
        }
        // 搜索条件 STORE_ID
        $condition = array('store_id'=>STORE_ID); // 商家id 
        $consignee=I('consignee');
        $condition['consignee']=array('like',"%$consignee%");
        
        if($begin && $end){
        	$condition['add_time'] = array('between',"$begin,$end");
        }
        I('order_sn') ? $condition['order_sn'] = trim(I('order_sn')) : false;
        I('order_status') != '' ? $condition['order_status'] = I('order_status') : false;
        I('pay_status') != '' ? $condition['pay_status'] = I('pay_status') : false;
        
        $pay_code=I('pay_code');
        $condition['pay_code']=array('like',"%$pay_code%");
        I('shipping_status') != '' ? $condition['shipping_status'] = I('shipping_status') : false;
        $mobile=I('mobile');

        $condition['ty_order.mobile']=array('like',"%$mobile%");
        //I('mobile') ? $condition['ty_order.mobile'] = trim(I('mobile')) : false;
        $sort_order = I('order_by','DESC').' '.I('sort');
		 $tguser_input=I('tguser');
        $tguser = M('users')->query("select nickname,user_id  from __PREFIX__users where seller_id =".STORE_ID." and  group_id in(5,7)");
		$tguser_m = array();
		$tguser_n = array();
		foreach($tguser as $v){
			$tguser_m[$v['user_id']] = $v['nickname'];
			$tguser_n[$v['nickname']] = $v['user_id'];
		}
		$nn = in_array($tguser_input,$tguser_m);
		if($nn) {
			$tgid = $tguser_n[$tguser_input];
			$condition['tuiguangid'] = $tgid;
		}
        $doctor_input=I('doctor_id');

        $doctor = M('users')->query("select nickname,user_id  from __PREFIX__users where   group_id =8");
       
        $tdoctor_m = array();
        $doctor_n = array();
        foreach($doctor as $v){
            $doctor_m[$v['user_id']] = $v['nickname'];
            $doctor_n[$v['nickname']] = $v['user_id'];
        }
        $aa = in_array($doctor_input,$doctor_m);

        if($aa) {
            $doctorid = $doctor_n[$doctor_input];
            $condition['doctor_id'] = $doctorid;
        }
		
        
        $goods_class=I('goods_class');
        $goods_name=I('goods_name');

        if($goods_class){
            $goods=M('goods')->field('goods_id')->where(array('cat_id3'=>$goods_class))->select();
       
        }elseif($goods_name){
             $goods=M('goods')->field('goods_id')->where("goods_name like '%$goods_name%' ")->select();
        }else{
             $goods=M('goods')->field('goods_id')->select();
        }
         foreach ($goods as $v)
            {
                $v = join(",",$v); //可以用implode将一维数组转换为用逗号连接的字符串
                $temp[] = $v;
            }
            $t="";
            foreach($temp as $v){
                $t.="'".$v."'".",";
            }
            $t=substr($t,0,-1);

        $orde=M('order_goods')->field('order_id')->where("goods_id in ($t)")->select();
       
         foreach ($orde as $v)
            {
                $v = join(",",$v); //可以用implode将一维数组转换为用逗号连接的字符串
                $temp1[] = $v;
            }
            $t1="";
            foreach($temp1 as $v){
                $t1.=$v.",";
            }
            $t1=substr($t1,0,-1);

        $condition['order_id']=array('in',$t1);
        $count = M('order')->where($condition)->count();
        $Page  = new AjaxPage($count,20);
        $show = $Page->show();
       if($Page->firstRow =='0'){
        $a=1;
       }else{
        $a=$Page->firstRow+1;
       }

        //获取订单列表
        $orderList = $orderLogic->getOrderList($condition,$sort_order,$Page->firstRow,$Page->listRows);
       
        $res = M('order')->where($condition)->order($order)->select();
        foreach($res as $k =>&$v){
            $v['total_price']=$v['goods_price'];
            $v['order_amount1']=$v['total_amount']-$v['yajin'];
        }
        $arr_sum1=array(); 
        $total_price = 0;
        $yajin = 0;
        $order_amount1=0;  
        foreach($res as $item){  
                $total_price +=  $item['total_amount'];
                $yajin +=  $item['yajin'];  
                $order_amount1 +=  $item['order_amount1'];  
        } 
        $order_status=I('order_status');
        $total_price=array('total_price'=>$total_price);
        $yajin=array('yajin'=>$yajin);
        $order_amount1=array('order_amount1'=>$order_amount1);
        $order_status=array('order_status'=>$order_status);
        $arr=array_merge($order_status,$total_price,$yajin,$order_amount1);

        foreach ($orderList as &$v){
            $goods=$v['goods_name'];
            $goods_num=0;
            foreach($goods as $v1){
               $goods_num+=$v1['goods_num'];
            }
            $v['goods_num']=$goods_num;
            $sl+=$goods_num;
            $zj+=$v['total_amount'];
           
             if($v['order_status']=='6'){
                   
                    $ys1=$v['yajin'];
            }else{
                 $ys1=$v['total_amount'];
            }

            if($v['order_status']=='6'){
                    $qk1=$v['order_amount1'];
            }else{
                if($v['total_amount']==$v['order_amount1']){
                    $qk1=$v['yajin'];
                }else{
                    $qk1=$v['order_amount'];
                }
            }
            $ys+=$ys1;
            $qk+=$qk1;

        }
        $tj=array(
            'sl'=>$sl,
            'zj'=>$zj,
            'ys'=>$ys,
            'qk'=>$qk,
            );
        $this->assign('a',$a);
        $this->assign('arr',$arr);
        $this->assign('orderList',$orderList);
        $this->assign('tj',$tj);
        $this->assign('page',$show);// 赋值分页输出
        $this->display();
    }

    
    /*
     * ajax 发货订单列表
    */
    public function ajaxdelivery(){
    	$orderLogic = new OrderLogic();
    	$condition = array('store_id'=>STORE_ID);
    	I('consignee') ? $condition['consignee'] = trim(I('consignee')) : false;
    	I('order_sn') != '' ? $condition['order_sn'] = trim(I('order_sn')) : false;
    	$shipping_status = I('shipping_status');
    	$condition['shipping_status'] = empty($shipping_status) ? array('neq',1) : $shipping_status;
		$condition['order_status'] = array('in','1,2,4');
    	$count = M('order')->where($condition)->count();
    	$Page  = new AjaxPage($count,10);
    	$show = $Page->show();
    	$orderList = M('order')->where($condition)->limit($Page->firstRow.','.$Page->listRows)->order('add_time DESC')->select();
    	$this->assign('orderList',$orderList);
    	$this->assign('page',$show);// 赋值分页输出
    	$this->display();
    }
    
    /**
     * 订单详情
     * @param int $id 订单id
     */
    public function detail($order_id){
        

        $orderLogic = new OrderLogic();
        $order = $orderLogic->getOrderInfo($order_id);
        
        $orderGoods = $orderLogic->getOrderGoods($order_id);
        $button = $orderLogic->getOrderButton($order);
        // 获取操作记录
        $action_log = M('order_action')->where(array('order_id'=>$order_id))->order('log_time desc')->select();
         $yjjl=M('order_yajing')->where("order_id=$order_id and status in(0,1)")->select();
        $this->assign('order',$order);
        $this->assign('action_log',$action_log);
        $this->assign('orderGoods',$orderGoods);
        $split = count($orderGoods) >1 ? 1 : 0;
        foreach ($orderGoods as $val){
        	if($val['goods_num']>1){
        		$split = 1;
        	}
        }
        $order_pay=M('order_pay')->where("order_id=$order_id")->select();
        $order_id1=I('order_id1');
        if($order_id1){
            $order_zs=M('order_goods')->where("order_id=$order_id1")->select();
             $this->assign('order_zs',$order_zs);
        }else{
            $order_sn=$order['order_sn'];
            $order1=M('order')->where("master_order_sn=$order_sn")->find();
            $id=$order1['order_id'];
            if($id){
                 $order_zs=M('order_goods')->where("order_id=$id")->select();
            $this->assign('order_zs',$order_zs);
            }
        }
        $this->assign('order_id1',$order_id1);
        $this->assign('order_pay',$order_pay);
        $this->assign('yjjl',$yjjl);
        $this->assign('split',$split);
        $this->assign('button',$button);
        
        $this->display();
    }

    /**
     * 订单编辑
     * @param int $id 订单id
     */
    public function edit_order(){
    	$order_id = I('order_id');
        $orderLogic = new OrderLogic();
        $order = $orderLogic->getOrderInfo($order_id);
        if($order['shipping_status'] != 0){
            $this->error('已发货订单不允许编辑');
            exit;
        } 
        
        $orderGoods = $orderLogic->getOrderGoods($order_id);
       	if(IS_POST)
        {
            $role_id_one = M('store')->where(array('store_id'=>STORE_ID))->find();
            $order['consignee'] = I('consignee');// 收货人
            $order['province'] = I('province'); // 省份
            $order['city'] = I('city'); // 城市
            $order['district'] = I('district'); // 县
            $order['address'] = I('address'); // 收货地址
            $order['mobile'] = I('mobile'); // 手机           
            $order['invoice_title'] = I('invoice_title');// 发票
            $order['admin_note'] = I('admin_note'); // 管理员备注 
            $order['shipping_code'] = I('shipping');// 物流方式
            $order['shipping_name'] = M('plugin')->where(array('status'=>1,'type'=>'shipping','code'=>I('shipping')))->getField('name');            
            $order['pay_code'] = I('payment');// 支付方式            
            $order['pay_name'] = M('plugin')->where(array('status'=>1,'type'=>'payment','code'=>I('payment')))->getField('name');
            $order['doctor_id']=I('doctor_id');                     
            $goods_id_arr = I("goods_id");
            $new_goods = $old_goods_arr = array();
            //################################订单添加商品
            if($goods_id_arr){
            	$new_goods = $orderLogic->get_spec_goods($goods_id_arr);
            	foreach($new_goods as $key => $val)
            	{
                    $data3[$key]['invId']   =   $val['goods_sn'];
                    $data3[$key]['invNumber']   =  '';
                    $data3[$key]['invName']   =  '';
                    $data3[$key]['invSpec']   =  '';
                    $data3[$key]['invSpec']   =  -1;
                    $data3[$key]['skuName']   =  '';
                    $data3[$key]['unitId']   =  0;
                    $data3[$key]['mainUnit']   =  '';
                    $data3[$key]['qty']   =   $val['goods_num'];
                    $data3[$key]['price']   =   $val['zj'];
                    $data3[$key]['discountRate']   =   0;
                    $data3[$key]['deduction']   =   0;
                    $data3[$key]['amount']   =   $val['zj'];
                    $data3[$key]['locationId']   =   STORE_ID;
                    $data3[$key]['locationName'] = $role_id_one['user_name'];
                    $data3[$key]['description'] =   $order['admin_note'];
            		$val['order_id'] = $order_id;
                        $val['store_id'] = STORE_ID;
            		$rec_id = M('order_goods')->add($val);//订单添加商品
            		if(!$rec_id)
            			$this->error('添加失败');

            	}
            }
            
            //################################订单修改删除商品
            $old_goods = I('old_goods');
            $old_good=I('old_good');

            foreach ($orderGoods as $val){
            	if(empty($old_goods[$val['rec_id']])){
            		M('order_goods')->where("rec_id=".$val['rec_id'])->delete();//删除商品
            	}else{
            		//修改商品数量
            		if($old_goods[$val['rec_id']] != $val['goods_num']){
            			$val['goods_num'] = $old_goods[$val['rec_id']];
            			M('order_goods')->where("rec_id=".$val['rec_id'])->save(array('goods_num'=>$val['goods_num']));
            		}
                    $order_price=$old_good[$val['rec_id']]/$old_goods[$val['rec_id']];
                    $order_price1=round($order_price,2);
                    
                    if($order_price1 !=$val['goods_price']){
                        $val['goods_price']=$order_price1;
                        $val['zj']=$old_good[$val['rec_id']];
                        $val['member_goods_price']=$order_price;
                        M('order_goods')->where("rec_id=".$val['rec_id'])->save(array('goods_price'=>$val['goods_price'],'member_goods_price'=>$val['member_goods_price']));
                    }
            		$old_goods_arr[] = $val;
            	}
                $data2[$key]['invId']   =   $val['goods_sn'];
                $data2[$key]['invNumber']   =  '';
                $data2[$key]['invName']   =  '';
                $data2[$key]['invSpec']   =  '';
                $data2[$key]['invSpec']   =  -1;
                $data2[$key]['skuName']   =  '';
                $data2[$key]['unitId']   =  0;
                $data2[$key]['mainUnit']   =  '';
                $data2[$key]['qty']   =   $val['goods_num'];
                $data2[$key]['price']   =   $val['zj'];
                $data2[$key]['discountRate']   =   0;
                $data2[$key]['deduction']   =   0;
                $data2[$key]['amount']   =   $val['zj'];
                $data2[$key]['locationId']   =   STORE_ID;
                $data2[$key]['locationName'] = $role_id_one['user_name'];
                $data2[$key]['description'] =   $order['admin_note'];
            }
          
            $goodsArr = array_merge($old_goods_arr,$new_goods);
            $data1['postData']['entries']   =   $goodsArr;
            $result = calculate_price($order['user_id'],$goodsArr,$order['shipping_code'],0,$order['province'],$order['city'],$order['district'],0,0,0,0);
            if($result['status'] < 0)
            {
            	$this->error($result['msg']);
            }
      
            //################################修改订单费用
            $order['goods_price']    = $result['result']['goods_price']; // 商品总价
            $order['shipping_price'] = $result['result']['shipping_price'];//物流费
            $order['order_amount']   = $result['result']['order_amount']; // 应付金额
            $order['total_amount']   = $result['result']['total_amount']; // 订单总价         
            $o = M('order')->where("order_id = $order_id and store_id =".STORE_ID)->save($order);
            $data1['postData']['id'] =   '-1';
            $data1['postData']['buId'] =   1;
            $data1['postData']['contactName'] =  $order['consignee'];
            $data1['postData']['salesId'] =  0;
            $data1['postData']['salesName'] =  '';
            $data1['postData']['date'] =  date("Y-m-d");
            $data1['postData']['deliveryDate'] =  date("Y-m-d");
            $data1['postData']['billNo'] =  $order['order_sn'];
            $data1['postData']['transType'] =   '150601';
            $data1['postData']['totalQty'] =   array_sum($number_count);
            $data1['postData']['totalDiscount'] =   0;
            $data1['postData']['totalAmount'] =   $order['order_amount'];
            $data1['postData']['description'] =   $order['admin_note'];
            $data1['postData']['disRate'] =   $order['give_integral']/$order['total_amount'];
            $data1['postData']['disAmount'] =   $order['total_amount']-$order['give_integral'];
            $data1['postData']['amount'] =   $order['give_integral'];
            $data1['postData']['billType'] =   'SALE';
            $data1['postData']['billDate'] =   date("Y-m-d");
            $data1['postData']['transTypeName'] =   '订货';
            $data1['postData']['totalTax'] =   0;
            $data1['postData']['totalTaxAmount'] =   0;
            $data1['postData']['uid'] =   $roleid;
            $data1['postData']['userName'] =   $role['user_name'];
            $data1['postData']['modifyTime'] =   date("Y-m-d H:i:s");
            $data1['postData']['deposit'] =   0;
            $data1['postData']['amountPaid'] =   0;
            if($data1['postData']['otherEntries']) $data1['postData']['otherEntries']  =   serialize($data1['postData']['otherEntries']);
            $seller_id = session('seller_id');
            $l = $orderLogic->orderActionLog($order,'edit','修改订单',$seller_id,1);//操作日志
            $request = httpRequest($url,'POST',encryptDecrypt(C('KEY_ERP'),$data1,0));
            if($o && $l  && json_decode($request)->status == 200){
                M('order')->commit();
                $this->success('修改成功',U('Admin/Order/detail',array('order_id'=>$order_id)));
            }else{
                M('order')->rollback();
                $this->success('修改失败',U('Admin/Order/detail',array('order_id'=>$order_id)));
            }
            exit;
			// $seller_id = session('seller_id');
   //          $l = $orderLogic->orderActionLog($order,'edit','修改订单',$seller_id,1);//操作日志
   //          if($o && $l){
   //          	$this->success('修改成功',U('Order/detail',array('order_id'=>$order_id)));
   //          }else{
   //          	$this->success('修改失败',U('Order/detail',array('order_id'=>$order_id)));
   //          }
   //          exit;
        }
        // 获取省份
        $province = M('region')->where(array('parent_id'=>0,'level'=>1))->select();
        //获取订单城市
        $city =  M('region')->where(array('parent_id'=>$order['province'],'level'=>2))->select();
        //获取订单地区
        $area =  M('region')->where(array('parent_id'=>$order['city'],'level'=>3))->select();
        //获取支付方式
        $payment_list = M('plugin')->where(array('status'=>1,'type'=>'payment'))->select();
        //获取配送方式
        $shipping_list = M('plugin')->where(array('status'=>1,'type'=>'shipping'))->select();
         $doctor = D('seller')->field('ty_users.nickname,ty_users.user_id')->join('ty_users on ty_seller.user_id= ty_users.user_id')->where(" ty_seller.group_id=8 and store_id=0 and is_admin=0 ")->select();
        $this->assign('doctor',$doctor);
        $this->assign('order',$order);
        $this->assign('province',$province);
        $this->assign('city',$city);
        $this->assign('area',$area);
        $this->assign('orderGoods',$orderGoods);
        $this->assign('shipping_list',$shipping_list);
        $this->assign('payment_list',$payment_list);
        $this->display();
    }
    /*
     * 拆分订单
     */
    public function split_order(){
    	$order_id = I('order_id');
    	$orderLogic = new OrderLogic();
    	$order = $orderLogic->getOrderInfo($order_id);
    	if($order['shipping_status'] != 0){
    		$this->error('已发货订单不允许编辑');
    		exit;
    	}
    	$orderGoods = $orderLogic->getOrderGoods($order_id);
    	if(IS_POST){
    		$data = I('post.');
    		//################################先处理原单剩余商品和原订单信息
    		$old_goods = I('old_goods');
    		foreach ($orderGoods as $val){
    			if(empty($old_goods[$val['rec_id']])){
    				M('order_goods')->where("rec_id=".$val['rec_id'])->delete();//删除商品
    			}else{
    				//修改商品数量
    				if($old_goods[$val['rec_id']] != $val['goods_num']){
    					$val['goods_num'] = $old_goods[$val['rec_id']];
    					M('order_goods')->where("rec_id=".$val['rec_id'])->save(array('goods_num'=>$val['goods_num']));
    				}
    				$oldArr[] = $val;//剩余商品
    			}
    			$all_goods[$val['rec_id']] = $val;//所有商品信息
    		}
    		$result = calculate_price($order['user_id'],$oldArr,array(STORE_ID => $order['shipping_code']),0,$order['province'],$order['city'],$order['district'],0,0,0,0);
    		if($result['status'] < 0)
    		{
    			$this->error($result['msg']);
    		}
    		//修改订单费用
    		$res['goods_price']    = $result['result']['goods_price']; // 商品总价
    		$res['order_amount']   = $result['result']['order_amount']; // 应付金额
    		$res['total_amount']   = $result['result']['total_amount']; // 订单总价
    		M('order')->where("order_id=".$order_id." and store_id =".STORE_ID)->save($res);
			//################################原单处理结束

    		//################################新单处理
    		for($i=1;$i<20;$i++){
    			if(!empty($_POST[$i.'_old_goods'])){
    				$split_goods[] = $_POST[$i.'_old_goods'];//新订单商品
    			}
    		}
    		foreach ($split_goods as $key=>$vrr){
    			foreach ($vrr as $k=>$v){
    				$all_goods[$k]['goods_num'] = $v;
    				$brr[$key][] = $all_goods[$k];
    			}
    		}

    		foreach($brr as $goods){
    			$result = calculate_price($order['user_id'],$goods,array(STORE_ID => $order['shipping_code']),0,$order['province'],$order['city'],$order['district'],0,0,0,0);
    			if($result['status'] < 0)
    			{
    				$this->error($result['msg']);
    			}
    			$new_order = $order;
    			$new_order['order_sn'] = date('YmdHis').mt_rand(1000,9999);
    			$new_order['parent_sn'] = $order['order_sn'];
    			//修改订单费用
    			$new_order['goods_price']    = $result['result']['goods_price']; // 商品总价
    			$new_order['order_amount']   = $result['result']['order_amount']; // 应付金额
    			$new_order['total_amount']   = $result['result']['total_amount']; // 订单总价
    			$new_order['add_time'] = time();
    			unset($new_order['order_id']);
    			$new_order_id = M('order')->add($new_order);//插入订单表
    			foreach ($goods as $vv){
    				$vv['order_id'] = $new_order_id;//新订单order_id
    				unset($vv['rec_id']);
                    $vv['store_id'] = STORE_ID;
    				$nid = M('order_goods')->add($vv);//插入订单商品表
    			}
    		}
    		//################################新单处理结束
    		$this->success('操作成功',U('Order/detail',array('order_id'=>$order_id)));
            exit;
    	}
    	
    	foreach ($orderGoods as $val){
    		$brr[$val['rec_id']] = array('goods_num'=>$val['goods_num'],'goods_name'=>getSubstr($val['goods_name'], 0, 35).$val['spec_key_name']);
    	}
    	$this->assign('order',$order);
    	$this->assign('goods_num_arr',json_encode($brr));
    	$this->assign('orderGoods',$orderGoods);
    	$this->display();
    }
    
    /*
     * 价钱修改
     */
    public function editprice($order_id){
        $orderLogic = new OrderLogic();
        $order = $orderLogic->getOrderInfo($order_id);
        $orderGoods = $orderLogic->getOrderGoods($order_id);
        //var_dump($order);
        $this->editable($order);
        if(IS_POST){        	
            $update['discount'] = I('post.discount');
            $update['shipping_price'] = I('post.shipping_price');
            $update['yajin2'] = I('post.yajin2');
            $update['yajin1'] = I('post.yajin1');
            $update['yajin']=$update['yajin1']+$update['yajin2'];
            $updatetime=I('post.updatetime');
            if($updatetime){
                $update['updatetime']=strtotime($updatetime);
            }else{
                 $update['updatetime']=time();
            }
            
	    $update['order_amount'] = $order['goods_price'] + $update['shipping_price'] - $update['discount'] - $order['user_money'] - $order['integral_money'] - $order['coupon_price']- $update['yajin'];
           if($order['goods_price']==$update['yajin'] ){
                $update['order_status']='1';
                foreach($orderGoods as $k => $v){
                    $v['give_integral']=$v['give_integral']*$v['goods_num'];
                accountLog($order['user_id'], 0,$v['give_integral'],"下单赠送积分");
                }
                
           }

          
            $row = M('order')->where(array('order_id'=>$order_id,'store_id'=>STORE_ID))->save($update);
            if(!$row){
                $this->success('没有更新数据',U('Order/editprice',array('order_id'=>$order_id)));
            }else{
                $update['order_id']=$order_id;
                $update['store_id']=STORE_ID;
                $update['yajing']=$_POST['yajin2'];
                $update['status']='1';
                M('order_yajing')->add($update);
                $this->success('操作成功',U('Order/detail',array('order_id'=>$order_id)));
            }
            exit;
        }
        $this->assign('order',$order);
        $this->display();
    }

    /**
     * 订单删除
     * @param int $id 订单id
     *  store_id   
     */
    public function delete_order($order_id){
    	$orderLogic = new OrderLogic();
        $b = M('order_yajing')->where(array('order_id'=>$order_id))->delete();
    	$del = $orderLogic->delOrder($order_id);

        if($del){
            $this->success('删除订单成功');
        }else{
        	$this->error('订单删除失败');
        }
    }
    
    /**
     * 订单取消付款
     */
    public function pay_cancel($order_id){
    	if(I('remark')){
    		$data = I('post.');
            
    		$note = array('退款到用户余额','已通过其他方式退款','不处理，误操作项');
    		if($data['refundType'] == 0 && $data['amount']>0){
    			accountLoga($data['user_id'], $data['amount'], 0,  '退款到用户余额');
    		}
    		$orderLogic = new OrderLogic();
            $store_id=session('store_id');
            $tk_time1=$data['tk_time'];
            if($tk_time1){
                $tk_time=strtotime($tk_time1);
            }else{
                $tk_time=time();
            }
            $orderLogic->orderProcessHandle($data['order_id'],'pay_cancel',$store_id,$tk_time);
            $order = $orderLogic->getOrderInfo($data['order_id']);
            $order_goods=M('order_goods')->where(array('order_id'=>$data['order_id']))->select();
            $user=M('users')->where(array('user_id'=>$data['user_id']))->find();
            foreach($order_goods as $k =>$v){
                $z=M('goods')->where(array('goods_id'=>$v['goods_id']))->find();
                $tjr=M('users')->where(array('user_id'=>$order['user_id']))->find();
                if($tjr['tjr_id']>'0'&&$z['zhuangtai']=='1'&&$tjr['tjr_cs']<'3'){
                    $tjr_cs1=M('users')->where(array('user_id'=>$tjr['tjr_id']))->find();
                    if($tjr_cs1['tjr_cs']>'0'){
                        $tjr_cs=$tjr_cs1['tjr_cs']-1;
                    }else{
                        $tjr_cs='0';
                    }
                    M('users')->where("user_id=$order[user_id]")->save(array('tjr_id'=>0,'is_distribut'=>0));
                    $a=M('users')->where("user_id=$tjr[tjr_id]")->save(array('tjr_cs'=>$tjr_cs));
                    tuikuan($tjr['tjr_id'], 0, $v['give_integral'], '推荐订单退款减少积分');
                    if($a){
                        tuikuan($order['user_id'], 0, $v['give_integral'], '退款减少积分');
                    }
                }elseif($tjr['tjr_cs']>='3'){
                    M('users')->where(array('user_id'=>$order['user_id']))->save(array('tjr_id'=>0,'tjr_cs'=>0,'is_distribut'=>0));
                    M('order')->where(array('order_id'=>$order['order_id']))->save(array('tk_status'=>'1','tk_time'=>time()));
                    $u=M('users')->where(array('tjr_id'=>$order['user_id']))->select();
                    foreach ($u as $key => $v) {

                        M('users')->where(array('user_id'=>$v['user_id']))->save(array('tjr_id'=>$v['user_id']));
                    }
                }else{
                    tuikuan($data['user_id'], 0, $data['amount'], '退款减少积分');
                }
                
                
            }
			$seller_id = session('seller_id');

    		$d = $orderLogic->orderActionLog($order,'退款',$data['remark'].':'.$note[$data['refundType']],$seller_id,1);
    		if($d){
    			exit("<script>window.parent.pay_callback(1);</script>");
    		}else{
    			exit("<script>window.parent.pay_callback(0);</script>");
    		}
    	}else{
    		$order = M('order')->join('ty_order_goods on ty_order.order_id=ty_order_goods.order_id')->where("ty_order.order_id=$order_id")->find();
    		$this->assign('order',$order);
    		$this->display();
    	}
    }

    /**
     * 订单打印
     * @param int $id 订单id
     */
    public function order_print(){
    	$order_id = I('order_id');
        $orderLogic = new OrderLogic();
        $order = $orderLogic->getOrderInfo($order_id);
        $order['province'] = getRegionName($order['province']);
        $order['city'] = getRegionName($order['city']);
        $order['district'] = getRegionName($order['district']);
        $order['full_address'] = $order['province'].' '.$order['city'].' '.$order['district'].' '. $order['address'];
        $orderGoods = $orderLogic->getOrderGoods($order_id);

    	$order['qk']=$order['total_amount']-$order['yajin'];
        $shop = tpCache('shop_info');
        $this->assign('order',$order);
        $this->assign('shop',$shop);
        $this->assign('orderGoods',$orderGoods);
        $template = I('template','print');
        $this->display($template);
    }

    /**
     * 快递单打印
     */
    public function shipping_print(){
        $order_id = I('get.order_id');
        $orderLogic = new OrderLogic();
        $order = $orderLogic->getOrderInfo($order_id);
        //查询是否存在订单及物流
        $shipping = M('plugin')->where(array('code'=>$order['shipping_code'],'type'=>'shipping'))->find();        
        if(!$shipping){
        	$this->error('物流插件不存在');
        }
		if(empty($shipping['config_value'])){
			$this->error('请联系平台管理员设置'.$shipping['name'].'打印模板');
		}
        $shop = M('store')->where(array('store_id'=>STORE_ID))->find();
        $shop['province'] = empty($shop['province_id']) ? '' : getRegionName($shop['province_id']);
        $shop['city'] = empty($shop['city_id']) ? '' : getRegionName($shop['city_id']);
        $shop['district'] = empty($shop['district']) ? '' : getRegionName($shop['district']);

        $order['province'] = getRegionName($order['province']);
        $order['city'] = getRegionName($order['city']);
        $order['district'] = getRegionName($order['district']);
        if(empty($shipping['config'])){
        	$config = array('width'=>840,'height'=>480,'offset_x'=>0,'offset_y'=>0);
        	$this->assign('config',$config);
        }else{
        	$this->assign('config',unserialize($shipping['config']));
        }
        $template_var = array("发货点-名称", "发货点-联系人", "发货点-电话", "发货点-省份", "发货点-城市",
        		 "发货点-区县", "发货点-手机", "发货点-详细地址", "收件人-姓名", "收件人-手机", "收件人-电话", 
        		"收件人-省份", "收件人-城市", "收件人-区县", "收件人-邮编", "收件人-详细地址", "时间-年", "时间-月", 
        		"时间-日","时间-当前日期","订单-订单号", "订单-备注","订单-配送费用");
        $content_var = array($shop['store_name'],$shop['seller_name'],$shop['store_phone'],$shop['province'],$shop['city'],
        	$shop['district'],$shop['store_phone'],$shop['store_address'],$order['consignee'],$order['mobile'],$order['phone'],
        	$order['province'],$order['city'],$order['district'],$order['zipcode'],$order['address'],date('Y'),date('M'),
        	date('d'),date('Y-m-d'),$order['order_sn'],$order['admin_note'],$order['shipping_price'],
        );
        $shipping['config_value'] = str_replace($template_var,$content_var, $shipping['config_value']);
        $this->assign('shipping',$shipping);
        $this->display("Plugin/print_express");
    }

    /**
     * 生成发货单
     */
    public function deliveryHandle(){
        $orderLogic = new OrderLogic();
		$data = I('post.');
		$res = $orderLogic->deliveryHandle($data,STORE_ID);
		if($res){
			$this->success('操作成功',U('Order/delivery_info',array('order_id'=>$data['order_id'])));
		}else{
			$this->success('操作失败',U('Order/delivery_info',array('order_id'=>$data['order_id'])));
		}
    }

    
    public function delivery_info(){
    	$order_id = I('order_id');
    	$orderLogic = new OrderLogic();
    	$order = $orderLogic->getOrderInfo($order_id);
    	$orderGoods = $orderLogic->getOrderGoods($order_id);
		$delivery_record = M('delivery_doc')->join('LEFT JOIN __SELLER__ ON __SELLER__.seller_id = __DELIVERY_DOC__.admin_id')->where('order_id='.$order_id)->select();
		if($delivery_record){
			$order['invoice_no'] = $delivery_record[count($delivery_record)-1]['invoice_no'];
		}
		$this->assign('order',$order);
		$this->assign('orderGoods',$orderGoods);
		$this->assign('delivery_record',$delivery_record);//发货记录
    	$this->display();
    }
    
    /**
     * 发货单列表
     */
    public function delivery_list(){
        $this->display();
    }
    /**
     * 退货单列表
     */
    public function return_list(){
        $this->display();
    }	
    /*
     * ajax 退货订单列表
     */
    public function ajax_return_list(){
        // 搜索条件        
        $order_sn =  trim(I('order_sn'));
        $order_by = I('order_by') ? I('order_by') : 'id';
        $sort_order = I('sort_order') ? I('sort_order') : 'desc';
        $status =  I('status','');
        
        $where = " store_id = ".STORE_ID;
        $order_sn && $where.= " and order_sn like '%$order_sn%' ";
        if($status !== '') 
            $where.= " and status = '$status' ";
        $count = M('return_goods')->where($where)->count();
        $Page  = new AjaxPage($count,20);
        $show = $Page->show();
        $list = M('return_goods')->where($where)->order("$order_by $sort_order")->limit("{$Page->firstRow},{$Page->listRows}")->select();        
        $goods_id_arr = get_arr_column($list, 'goods_id');
        if(!empty($goods_id_arr))
            $goods_list = M('goods')->where("goods_id in (".implode(',', $goods_id_arr).")")->getField('goods_id,goods_name');
        $this->assign('goods_list',$goods_list);
        $this->assign('list',$list);
        $this->assign('page',$show);// 赋值分页输出
        $this->display();
    }
    
    /**
     * 删除某个退换货申请
     */
    public function return_del(){
        $id = I('get.id');
        M('return_goods')->where("id = $id and store_id = ".STORE_ID)->delete(); 
        $this->success('成功删除!');
    }
    /**
     * 退换货操作
     */
    public function return_info()
    {
        $id = I('id');
        $return_goods = M('return_goods')->where("id= $id  and store_id = ".STORE_ID)->find();
        empty($return_goods) && $this->error("参数有误");
        
        if($return_goods['imgs'])            
             $return_goods['imgs'] = explode(',', $return_goods['imgs']);
        $user = M('users')->where("user_id = {$return_goods[user_id]}")->find();
        $goods = M('goods')->where("goods_id = {$return_goods[goods_id]}")->find();
        $order_goods = M('order_goods')->where("order_id ={$return_goods['order_id']} and goods_id = {$return_goods['goods_id']} and spec_key = '{$return_goods['spec_key']}'")->find();
        $type_msg = array('退换','换货');
        $status_msg = array('未处理','处理中','已完成');
        if(IS_POST)
        {            
            $data['status'] = I('status');
            $data['remark'] = I('remark');                                    
            $note ="退换货:{$type_msg[$return_goods['type']]}, 状态:{$status_msg[$data['status']]},处理备注：{$data['remark']}";
            $result = M('return_goods')->where("id= $id  and store_id = ".STORE_ID)->save($data);    
            if($result)
            {                    	
                // 如果是换货
                if($return_goods['type'] == 1)
                {
                    $where = " order_id = ".$return_goods['order_id']." and goods_id=".$return_goods['goods_id'];
                    M('order_goods')->where($where)->save(array('is_send'=>2));//更改商品状态                           
                }
                $orderLogic = new OrderLogic();
                $seller_id = session('seller_id');
                $order = $orderLogic->getOrderInfo($return_goods['order_id']);
                $log = $orderLogic->orderActionLog($order,'订单退货',$note,$seller_id,1);
                $this->success('修改成功!');            
                exit;
            }  
        }        
        
        $this->assign('id',$id); // 用户
        $this->assign('user',$user); // 用户
        $this->assign('goods',$goods);// 商品        
        $this->assign('order_goods',$order_goods);// 商品列表
        $this->assign('return_goods',$return_goods);// 退换货               
        $this->display();
    }
    
    /**
     * 管理员生成申请退货单
     */
    public function add_return_goods()
   {                
            $order_id = I('order_id'); 
            $goods_id = I('goods_id');
                
            $return_goods = M('return_goods')->where("order_id = $order_id and goods_id = $goods_id")->find();            
            if(!empty($return_goods))
            {
                $this->error('已经提交过退货申请!',U('Admin/Order/return_list'));
                exit;
            }
            $order = M('order')->where("order_id = $order_id")->find();
            
            $data['order_id'] = $order_id; 
            $data['order_sn'] = $order['order_sn']; 
            $data['goods_id'] = $goods_id; 
            $data['addtime'] = time(); 
            $data['user_id'] = $order[user_id];            
            $data['remark'] = '管理员申请退换货'; // 问题描述            
            M('return_goods')->add($data);            
            $this->success('申请成功,现在去处理退货',U('Admin/Order/return_list'));
            exit;
    }

    /**
     * 订单操作
     * @param $id
     */
    public function order_action(){    	
        $orderLogic = new OrderLogic();
        $action = I('get.type');
       
        $order_id = I('get.order_id');
        $order_id1 = I('get.order_id1');
        if($action && $order_id){
			 $order = $orderLogic->getOrderInfo($order_id);
                if($action=='invalid'&&$order['order_status']=='1'){
                    $order_id=$order['order_id'];
                    $sql="select * from ty_order_goods where order_id=$order_id";
                    $Model = M();
                    $result = $Model->query($sql);
                    $tjr_id=M('users')->where(array('user_id'=>$order['user_id']))->find();
                    foreach($result as $k =>$v){
                        $z=M('goods')->where(array('goods_id'=>$v['goods_id']))->find();
                        if($tjr_id['tjr_id']>'0'&&$z['zhuangtai']=='1'){
                            $tjr_cs1=M('users')->where(array('user_id'=>$tjr_id['tjr_id']))->find();
                            if($tjr_cs1['tjr_cs']>'0'){
                                $tjr_cs=$tjr_cs1['tjr_cs']-1;
                            }else{
                                $tjr_cs='0';
                            }
                            M('users')->where("user_id=$order[user_id]")->save(array('tjr_id'=>0,'is_distribut'=>0));
                            $a=M('users')->where("user_id=$tjr_id[tjr_id]")->save(array('tjr_cs'=>$tjr_cs));
                            tuikuan($tjr_id['tjr_id'], 0, $v['give_integral'],  '推荐订单无效减少积分');
                            if($a){
                             tuikuan($order['user_id'], 0, $v['give_integral'],  '订单无效减少积分');
                            }
                        }else{
                            tuikuan($order['user_id'], 0, $v['give_integral'],  '无效订单减少积分');
                        }
                    }
                }elseif($order['order_status']=='6'){
                   M('order')->where("order_id=$order[order_id]")->save(array('total_amount'=>$order['yajin'],'yajin'=>'0','order_amount'=>$order['yajin']));
                    accountLog($order['user_id'], 0,$order['yajin'],"押金商品无效，押金赠送积分");
                }
             $a = $orderLogic->orderProcessHandle($order_id,$action,STORE_ID);
             if($order_id1){
                $orderLogic->orderProcessHandle($order_id1,$action,STORE_ID);
             }
                
             $seller_id = session('seller_id');
        	 $res = $orderLogic->orderActionLog($order,$action,I('note'),$seller_id,1);
        	 if($res && $a){
        	 	exit(json_encode(array('status' => 1,'msg' => '操作成功')));
        	 }else{
        	 	exit(json_encode(array('status' => 0,'msg' => '操作失败')));
        	 }
        }else{
        	$this->error('参数错误',U('Admin/Order/detail',array('order_id'=>$order_id)));
        }
    }
    
    public function order_log(){
    	$timegap = I('timegap');
    	if($timegap){
    		$gap = explode('-', $timegap);
    		$begin = strtotime($gap[0]);
    		$end = strtotime($gap[1])+86399;
    	}
    	$condition = array();
    	$log =  M('order_action');
    	if($begin && $end){
    		$condition['log_time'] = array('between',"$begin,$end");
    	}
    	$admin_id = I('admin_id');
		if($admin_id >0 ){
			$condition['action_user'] = $admin_id;
		}
		$condition['store_id'] = STORE_ID;
    	$count = $log->where($condition)->count();
    	$Page = new \Think\Page($count,20);
    	foreach($condition as $key=>$val) {
    		$Page->parameter[$key] = urlencode($val);
    	}
    	$show = $Page->show();
    	$list = $log->where($condition)->order('action_id desc')->limit($Page->firstRow.','.$Page->listRows)->select();
    	$this->assign('list',$list);
    	$this->assign('page',$show);   	
    	$seller = M('seller')->getField('seller_id,seller_name');
    	$this->assign('admin',$seller);    	
    	$this->display();
    }

    /**
     * 检测订单是否可以编辑
     * @param $order
     */
    private function editable($order){
        if($order['shipping_status'] != 0){
            $this->error('已发货订单不允许编辑');
            exit;
        }
        return;
    }

    public function export_order() 
    {
    	//搜索条件        
		$where = "where store_id =".STORE_ID." ";
		$consignee = I('consignee');
		$tguser_input=I('tguser');
		if($consignee){
			$where .= " AND consignee like '%$consignee%' ";
		}
		$order_sn =  I('order_sn');
		if($order_sn){
			$where .= " AND order_sn = '$order_sn' ";
		}
		if(I('order_status')){
			$where .= " AND order_status = ".I('order_status');
		}
        $goods_class=I('goods_class');
        $goods_name=I('goods_name');

        if($goods_class){
            $goods=M('goods')->field('goods_id')->where(array('cat_id3'=>$goods_class))->select();
       
        }elseif($goods_name){
             $goods=M('goods')->field('goods_id')->where(array('goods_name'=>$goods_name))->select();
        }else{
            $goods=M('goods')->field('goods_id')->select();
        }
         foreach ($goods as $v)
            {
                $v = join(",",$v); //可以用implode将一维数组转换为用逗号连接的字符串
                $temp[] = $v;
            }
            $t="";
            foreach($temp as $v){
                $t.="'".$v."'".",";
            }
            $t=substr($t,0,-1);

             $orde=M('order_goods')->field('order_id')->where("goods_id in ($t)")->select();
         foreach ($orde as $v)
            {
                $v = join(",",$v); //可以用implode将一维数组转换为用逗号连接的字符串
                $temp1[] = $v;
            }
            $t1="";
            foreach($temp1 as $v){
                $t1.=$v.",";
            }
            $t1=substr($t1,0,-1);
            if($t1){
                $where .= " AND order_id in ($t1)";
            }
		if($tguser_input){
			$tguser = M('users')->query("select nickname,user_id  from __PREFIX__users where seller_id =".STORE_ID." and  group_id in(5,7)");
			$tguser_m = array();
			$tguser_n = array();
			foreach($tguser as $v){
				$tguser_m[$v['user_id']] = $v['nickname'];
				$tguser_n[$v['nickname']] = $v['user_id'];
			}
			$nn = in_array($tguser_input,$tguser_m);
			if($nn) {
				$tgid = $tguser_n[$tguser_input];
				$where .= " AND tuiguangid = ".$tgid;
			}
		}
		$timegap = I('timegap');
		if($timegap){
			$gap = explode('-', $timegap);
			$begin = strtotime($gap[0]);
			$end = strtotime($gap[1])+86399;
			$where .= " AND add_time>=$begin and add_time<=$end";
		}
	$region	= M('region')->getField('id,name');
                
	$sql = "select *,FROM_UNIXTIME(add_time,'%Y-%m-%d') as create_time from __PREFIX__order $where order by order_id";
    	$orderList = D()->query($sql); 
    	$strTable ='<table width="500" border="1">';
    	$strTable .= '<tr>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:120px;">订单编号</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="100">会员名称</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">商品名称</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">购买数量</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">总金额</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">已付金额</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">欠款金额</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">订单状态</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">支付状态</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">理疗师</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">医生</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">支付方式</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">发药状态</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">下单时间</td>';
        $strTable .= '</tr>';
    	
    	foreach($orderList as $k=>$val){

    		$strTable .= '<tr>';
    		$strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;'.$val['order_sn'].'</td>';
    		$strTable .= '<td style="text-align:left;font-size:12px;">'.$val['consignee'].': '.$val['mobile'].' </td>';
            $orderGoods = D('order_goods')->where('order_id='.$val['order_id'])->select();
    		$strGoods="";
            foreach($orderGoods as $goods){
                $strGoods .= " 商品名称：".$goods['goods_name'];
                if ($goods['spec_key_name'] != '') $strGoods .= " 规格：".$goods['spec_key_name'];
                $strGoods .= "<br />";
            }
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$strGoods.' </td>';
            $goods_num=0;
            foreach($orderGoods as $goods){
               $goods_num+=$goods['goods_num'];
            }
            unset($orderGoods);
    		$strTable .= '<td style="text-align:left;font-size:12px;">'.$goods_num.'</td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['total_amount'].'</td>';
            if($val['yajin']=='0.00'&&$val['order_status']=='6'){
                $qian='0';
                $strTable .= '<td style="text-align:left;font-size:12px;">'.$qian.'</td>';
                $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['order_amount'].'</td>';
            }elseif($val['order_status']=='6'){
                $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['yajin'].'</td>';
                $qian=$val['total_amount']-$val['yajin'];
                $strTable .= '<td style="text-align:left;font-size:12px;">'.$qian.'</td>';
            }else{
                $qian='0';
                $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['order_amount'].'</td>';
                $strTable .= '<td style="text-align:left;font-size:12px;">'.$qian.'</td>';
            }
            if($val['order_status']=='0'){
                 $strTable .= '<td style="text-align:left;font-size:12px;">'.待确认.'</td>';
            }elseif($val['order_status']=='1'){
                $strTable .= '<td style="text-align:left;font-size:12px;">'.已确认.'</td>';
            }elseif($val['order_status']=='2'){
                $strTable .= '<td style="text-align:left;font-size:12px;">'.已收货.'</td>';
            }elseif($val['order_status']=='3'){
                $strTable .= '<td style="text-align:left;font-size:12px;">'.已取消.'</td>';
            }elseif($val['order_status']=='4'){
                $strTable .= '<td style="text-align:left;font-size:12px;">'.已完成.'</td>';
            }elseif($val['order_status']=='5'){
                $strTable .= '<td style="text-align:left;font-size:12px;">'.已作废.'</td>';
            }elseif($val['order_status']=='6'){
                $strTable .= '<td style="text-align:left;font-size:12px;">'.部分支付.'</td>';
            }elseif($val['order_status']=='7'){
                $strTable .= '<td style="text-align:left;font-size:12px;">'.积分兑换.'</td>';
            }elseif($val['order_status']=='8'){
                $strTable .= '<td style="text-align:left;font-size:12px;">'.已退款.'</td>';
            }elseif($val['order_status']=='9'){
                $strTable .= '<td style="text-align:left;font-size:12px;">'.赠送.'</td>';
            }
    		if($val['order_status']=='6'){
                $strTable .= '<td style="text-align:left;font-size:12px;">'.欠款.'</td>';
            }else{
                $strTable .= '<td style="text-align:left;font-size:12px;">'.$this->pay_status[$val['pay_status']].'</td>';
            }
            
            $tguserid = $val['tuiguangid'];
            $tguserinfo = M('users')->where('user_id='.$tguserid)->find(); 
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$tguserinfo['nickname'].'</td>';    
    		
    		$doctor_id = $val['doctor_id'];
            $doctor_id = M('users')->where('user_id='.$doctor_id)->find(); 
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$doctor_id['nickname'].'</td>'; 
    		$strTable .= '<td style="text-align:left;font-size:12px;">'.$val['pay_name'].'</td>'; 
            if($val['shipping_status']=='0'){
                $strTable .= '<td style="text-align:left;font-size:12px;">'.未发货.'</td>';
            }elseif($val['shipping_status']=='1'){
                $strTable .= '<td style="text-align:left;font-size:12px;">'.已发货.'</td>';
            }elseif($val['shipping_status']=='1'){
                $strTable .= '<td style="text-align:left;font-size:12px;">'.部分发货.'</td>';
            }
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['create_time'].'</td>';
    		$strTable .= '</tr>';
    	}
    	$strTable .='</table>';
    	unset($orderList);
    	downloadExcel($strTable,'order');
    	exit();
    }
   
    /**
     * 添加一笔订单
     */
    public function add_order()
    {
        $order = array('store_id'=>STORE_ID);
        //  获取省份
        $province = M('region')->where(array('parent_id'=>0,'level'=>1))->select();
        //  获取订单城市
        $city =  M('region')->where(array('parent_id'=>$order['province'],'level'=>2))->select();
        //  获取订单地区
        $area =  M('region')->where(array('parent_id'=>$order['city'],'level'=>3))->select();

        //  获取配送方式
        $shipping_list = M('plugin')->where(array('status'=>1,'type'=>'shipping'))->select();
        //  获取支付方式
        $payment_list = M('plugin')->where(array('status'=>1,'type'=>'payment'))->select();
        //  获取医生
        $doctor = D('seller')->field('ty_users.nickname,ty_users.user_id')->join('ty_users on ty_seller.user_id= ty_users.user_id')->where(" ty_seller.group_id=8 and store_id=0 and is_admin=0 ")->select();
        $user_id=I('user_id');
        $user=M('users')->where(array('user_id'=>$user_id))->find();
        //var_dump($user);
        if(IS_POST)
        {
            M('order')->startTrans();
            $role_id_one = M('store')->where(array('store_id'=>STORE_ID))->find();
            $order['user_id'] = I('user_id');// 用户id 可以为空
            $user_id = I('user_id');// 用户id 可以为空
            $order['consignee'] = I('consignee');// 收货人
            $order['province'] = I('province'); // 省份
            $order['city'] = I('city'); // 城市
            $order['district'] = I('district'); // 县
            $order['address'] = I('address'); // 收货地址
            $order['mobile'] = I('mobile'); // 手机           
            $order['invoice_title'] = I('invoice_title');// 发票
            $order['admin_note'] = I('admin_note'); // 管理员备注            
            $order['order_sn'] = date('YmdHis').mt_rand(1000,9999); // 订单编号;
            $order['admin_note'] = I('admin_note'); // 
            $add_time=$_POST['add_time'];
            if($add_time){
                $order['add_time'] = strtotime($add_time);// 
            }else{
                 $order['add_time'] = time(); 
            }                  
            $order['shipping_code'] = I('shipping');// 物流方式
            $order['shipping_name'] = M('plugin')->where(array('status'=>1,'type'=>'shipping','code'=>I('shipping')))->getField('name');             
            $zj=I('zj');
            $a=array_filter($zj);
            $payment=array_keys($a);
            $pay_name=array();
            foreach($payment as $v){
                $pay_name[]=M('plugin')->where(array('status'=>1,'type'=>'payment','code'=>$v))->getField('name');
                
            }
            $pay_name=implode(",", $pay_name);
            $payment=implode(",", $payment);
            $order['pay_code']=$payment;   
            $order['pay_name']=$pay_name;            
            $order['yajin']=I('yajin');
            $order['doctor_id']=I('doctor_id');
            $yajin=I('yajin');
            if($yajin==""){
                $order['order_status']='1';
            }else{
                $order['order_status']='6';
            }
            $order['pay_status']='1';
            $order['shipping_status']='0';
            $uid1=I('uid1');
            $goods_id_arr = I("goods_id");
            $goods=I("goods_id1");
            $orderLogic = new OrderLogic();
            $order_goods = $orderLogic->get_spec_goods($goods_id_arr);
            $order_goods1 = $orderLogic->get_spec_goods($goods);
            
            foreach($order_goods as $k =>$v){
                if($v['zhuangtai']=='1'){
                    $tj=M('tj')->where(array('user_id'=>$order['user_id'],'tjr_id'=>$uid1))->find();
                    if($tj){
                        $this->error('该推荐人已经推荐过您了,请勿重复推荐');
                    }
                    $t=M('users')->where(array('user_id'=>$uid1))->find();
                    if($t['tjr_cs']>='3'){
                         $this->error('该推荐人已满3次,请先退款');
                    }
                    $s=M('users')->where(array('user_id'=>$order['user_id'],'is_distribut'=>'1'))->find();
                    if($s){
                         $this->error('您已购买此分销商品，请勿重复购买');
                    }
               }/*elseif ($v['goods_price']=='0') {
                    $this->error('请填写商品价格');
               }*/
            }
            $result = calculate_price($order['user_id'],$order_goods, array(STORE_ID => $order['shipping_code']), 0,$order[province],$order[city],$order[district],0,0,0,0);  
            if($result['status'] < 0)	
            {
                 $this->error($result['msg']);      
            } 
           $order['roleid'] = $role_id_one['roleid'];
           $order['tuiguangid'] = I('tguser_id');
           $order['goods_price']    = $result['result']['goods_price']; // 商品总价
           $order['shipping_price'] = $result['result']['store_shipping_price'][STORE_ID]; //物流费
           $order['order_amount']   = $result['result']['order_amount']; // 应付金额
           $order['total_amount']   = $result['result']['total_amount']; // 订单总价
           $order['give_integral']   = $result['result']['give_integral']; // 订单总积分
           $order['exchange_integral']   = $result['result']['exchange_integral']; // 订单总积分
          
           //积分兑换查询会员积分
           $pay_points=M('users')->where(array('user_id'=>I('user_id')))->getField('pay_points');
           if($order['pay_code']=='jifen'){
                if($pay_points >= $order['exchange_integral']){
                     $order['order_status']='7';
                    // 添加订单
                    $order_id = M('order')->add($order);
                    if($order_id){
                        foreach($order_goods as $key => $val){
                            $val['order_id'] = $order_id;
                            $val['store_id'] = STORE_ID;
                            $val['exchange_integral']=$val['exchange_integral'];
                            $data1['postData']['entries'][$key]['invId']   =   $val['goods_sn'];
                            $data1['postData']['entries'][$key]['invNumber']   =  '';
                            $data1['postData']['entries'][$key]['invName']   =  '';
                            $data1['postData']['entries'][$key]['invSpec']   =  '';
                            $data1['postData']['entries'][$key]['invSpec']   =  -1;
                            $data1['postData']['entries'][$key]['skuName']   =  '';
                            $data1['postData']['entries'][$key]['unitId']   =  0;
                            $data1['postData']['entries'][$key]['mainUnit']   =  '';
                            $data1['postData']['entries'][$key]['qty']   =   $val['goods_num'];
                            $data1['postData']['entries'][$key]['price']   =   $val['zj'];
                            $data1['postData']['entries'][$key]['discountRate']   =   0;
                            $data1['postData']['entries'][$key]['deduction']   =   0;
                            $data1['postData']['entries'][$key]['amount']   =   $val['zj'];
                            $data1['postData']['entries'][$key]['locationId']   =   STORE_ID;
                            $data1['postData']['entries'][$key]['locationName'] = $role_id_one['store_name'];
                            $data1['postData']['entries'][$key]['description'] =   $order['admin_note'];
                             accountLoga($order['user_id'], 0,$val['exchange_integral'],"积分兑换商品");
                            $rec_id = M('order_goods')->add($val);
                            if(!$rec_id)                 
                            $this->error('添加失败');                                  
                        }
                        $data1['postData']['id'] =   '-1';
                        $data1['postData']['buId'] =   1;
                        $data1['postData']['contactName'] =  $order['consignee'];
                        $data1['postData']['salesId'] =  0;
                        $data1['postData']['salesName'] =  '';
                        $data1['postData']['date'] =  date("Y-m-d");
                        $data1['postData']['deliveryDate'] =  date("Y-m-d");
                        $data1['postData']['billNo'] =  $order['order_sn'];
                        $data1['postData']['transType'] =   '150601';
                        $data1['postData']['totalQty'] =   array_sum($number_count);
                        $data1['postData']['totalDiscount'] =   0;
                        $data1['postData']['totalAmount'] =   $order['order_amount'];
                        $data1['postData']['description'] =   $order['admin_note'];
                        $data1['postData']['disRate'] =   $order['give_integral']/$order['total_amount'];
                        $data1['postData']['disAmount'] =   $order['total_amount']-$order['give_integral'];
                        $data1['postData']['amount'] =   $order['give_integral'];
                        $data1['postData']['billType'] =   'SALE';
                        $data1['postData']['billDate'] =   date("Y-m-d");
                        $data1['postData']['transTypeName'] =   '订货';
                        $data1['postData']['totalTax'] =   0;
                        $data1['postData']['totalTaxAmount'] =   0;
                        $data1['postData']['uid'] =   STORE_ID;
                        $data1['postData']['userName'] =   $role_id_one['store_name'];
                        $data1['postData']['modifyTime'] =   date("Y-m-d H:i:s");
                        $data1['postData']['deposit'] =   0;
                        $data1['postData']['amountPaid'] =   0;
                        //accountLoga($order['user_id'], 0,$order['give_integral'],"积分兑换商品");
                        $request = httpRequest($url,'POST',encryptDecrypt(C('KEY_ERP'),$data1,0));
                        accountLoga($order['user_id'], 0,$order['give_integral'],"积分兑换商品");
                        if(json_decode($request)->status == 200){
                            M('order')->commit();
                            $this->success('添加商品成功',U("Admin/Order/index",array('order_id'=>$order_id)));
                            exit();
                        }else{
                            M('order')->rollback();
                            $this->error('添加失败');
                        }    
                    }else{
                        $this->error('添加失败');
                    }                
                }else{
                    $this->error('积分不足,兑换失败');
                }
           }else{
                $order_id = M('order')->add($order);
                foreach($a as$k => $v1){
                    $pay_name=M('plugin')->where(array('status'=>1,'type'=>'payment','code'=>$k))->getField('name');
                    M('order_pay')->add(array('order_id'=>$order_id,'pay_name'=>$pay_name,'jinen'=>$v1));
                }
                if($order_id){
                    if($order_goods1){
                        $order_sn=M('order')->where("order_id=$order_id")->find();
                        $data['master_order_sn']=$order_sn['order_sn'];
                        $data['user_id']=$order['user_id'];
                        $data['order_status']='9';
                        $data['mobile']=$order['mobile'];// 手机  
                        $data['consignee']=$order['consignee'];
                        $data['add_time']=$order['add_time'];
                        $data['store_id']=STORE_ID;
                        $data['roleid']=$role_id_one['roleid'];
                        $data['tuiguangid']=I('tguser_id');
                        $data['order_sn'] = date('YmdHis').mt_rand(1000,9999); // 订单编号;
                        $or=M('order')->add($data);
                        if($or){
                            foreach($order_goods1 as $v){
                                $v['order_id'] = $or;
                                $v['store_id'] = STORE_ID;
                                $rec_id = M('order_goods')->add($v);
                            }
                            foreach($order_goods1 as $key => $val){
                                $data1['postData']['otherEntries'][$key]['giveGoodsSn']     =   $val['goods_sn'];
                                $data1['postData']['otherEntries'][$key]['giveGoodsNum']    =   $val['goods_num'];
                            }
                        }
                    }
                    foreach($order_goods as $key => $val){
                        $val['order_id'] = $order_id;
                        $val['store_id'] = STORE_ID;
                        $zhuangtai=$val['zhuangtai'];
                        if($zhuangtai=='1'){
                            if($uid1=='0'){ 
                                M('users')->where(array('user_id'=>$user_id))->save(array('is_distribut'=>'1','tjr_id'=>$order['user_id']));
                            }else{
                                $tjr_cs=M('users')->field('tjr_cs')->where(array('user_id'=>$uid1))->find();
                                $tjr_cs=$tjr_cs['tjr_cs']+1;
                                M('users')->where(array('user_id'=>$user_id))->save(array('is_distribut'=>'1','tjr_id'=>$uid1));
                                M('users')->where(array('user_id'=>$uid1))->save(array('tjr_cs'=>$tjr_cs));
                                M('tj')->add(array('user_id'=>$user_id,'tjr_id'=>$uid1));
                                $val['give_integral']=$val['give_integral'];
                                accountLog($uid1, 0,$val['give_integral'],"推荐人赠送积分"); 
                            }
                        }
                        if($order['order_status']!='6'){
                            $val['give_integral']=$val['give_integral'];
                            accountLog($order['user_id'], 0,$val['give_integral'],"下单赠送积分");
                        }
                        $rec_id = M('order_goods')->add($val);
                         if($yajin){
                            $val['yajing']=$yajin;
                            $val['updatetime']=$order['add_time'];
                            $val['status']=0;
                            $val['store_id']=STORE_ID;
                            M('order_yajing')->add($val);
                        }
                        if(!$rec_id)                 
                        $this->error('添加失败');
                        $data1['postData']['entries'][$key]['invId']   =   $val['goods_sn'];
                        $data1['postData']['entries'][$key]['invNumber']   =  '';
                        $data1['postData']['entries'][$key]['invName']   =  '';
                        $data1['postData']['entries'][$key]['invSpec']   =  '';
                        $data1['postData']['entries'][$key]['invSpec']   =  -1;
                        $data1['postData']['entries'][$key]['skuName']   =  '';
                        $data1['postData']['entries'][$key]['unitId']   =  0;
                        $data1['postData']['entries'][$key]['mainUnit']   =  '';
                        $data1['postData']['entries'][$key]['qty']   =   $val['goods_num'];
                        $data1['postData']['entries'][$key]['price']   =   $val['zj'];
                        $data1['postData']['entries'][$key]['discountRate']   =   0;
                        $data1['postData']['entries'][$key]['deduction']   =   0;
                        $data1['postData']['entries'][$key]['amount']   =   $val['zj'];
                        $data1['postData']['entries'][$key]['locationId']   =   STORE_ID;
                        $data1['postData']['entries'][$key]['locationName'] = $role_id_one['store_name'];
                        $data1['postData']['entries'][$key]['description'] =   $order['admin_note'];                                  
                    }
                    $data1['postData']['id'] =   '-1';
                    $data1['postData']['buId'] =   1;
                    $data1['postData']['contactName'] =  $order['consignee'];
                    $data1['postData']['salesId'] =  0;
                    $data1['postData']['salesName'] =  '';
                    $data1['postData']['date'] =  date("Y-m-d");
                    $data1['postData']['deliveryDate'] =  date("Y-m-d");
                    $data1['postData']['billNo'] =  $order['order_sn'];
                    $data1['postData']['transType'] =   '150601';
                    $data1['postData']['totalQty'] =   array_sum($number_count);
                    $data1['postData']['totalDiscount'] =   0;
                    $data1['postData']['totalAmount'] =   $order['order_amount'];
                    $data1['postData']['description'] =   $order['admin_note'];
                    $data1['postData']['disRate'] =   $order['give_integral']/$order['total_amount'];
                    $data1['postData']['disAmount'] =   $order['total_amount']-$order['give_integral'];
                    $data1['postData']['amount'] =   $order['give_integral'];
                    $data1['postData']['billType'] =   'SALE';
                    $data1['postData']['billDate'] =   date("Y-m-d");
                    $data1['postData']['transTypeName'] =   '订货';
                    $data1['postData']['totalTax'] =   0;
                    $data1['postData']['totalTaxAmount'] =   0;
                    $data1['postData']['uid'] =   $roleid;
                    $data1['postData']['userName'] =   $role['user_name'];
                    $data1['postData']['modifyTime'] =   date("Y-m-d H:i:s");
                    $data1['postData']['deposit'] =   0;
                    $data1['postData']['amountPaid'] =   0;
                    if($data1['postData']['otherEntries']) $data1['postData']['otherEntries']  =   serialize($data1['postData']['otherEntries']);

                    $request = httpRequest($url,'POST',encryptDecrypt(C('KEY_ERP'),$data1,0));
                    if(json_decode($request)->status == 200){
                        M('order')->commit();
                        $this->success('添加商品成功',U("Admin/Order/index",array('order_id'=>$order_id)));
                        exit();
                    }else{
                        M('order')->rollback();
                        $this->error('添加失败');
                    }
                }else{
                    $this->error('添加失败');
                }                
            }
        }     
        $tguser_n = M('seller')->field('user_id')->where("store_id = ".STORE_ID." and group_id in(5,7)")->select();
        foreach ($tguser_n as $key => $value) {
            $tguser_m[] = $value['user_id'];
        }
        $tguser_sql = implode(',',$tguser_m);
        $tguser = M('users')->field('user_id,nickname')->where("user_id in($tguser_sql)")->select();
        $this->assign('tguser',$tguser);
        $this->assign('shipping_list',$shipping_list);
        $this->assign('payment_list',$payment_list);
        $this->assign('province',$province);
        $this->assign('city',$city);
        $this->assign('area',$area);
        $this->assign('user',$user); 
        $this->assign('doctor',$doctor);       
        $this->display();
    }
    
    /**
     * 选择搜索商品
     */
    public function search_goods()
    {
    	$brandList =  M("brand")->select();
    	$categoryList =  M("goods_category")->select();
    	$this->assign('categoryList',$categoryList);
    	$this->assign('brandList',$brandList);   	
    	$where = ' store_id=0 and  is_on_sale = 1 ';//搜索条件
    	I('intro')  && $where = "$where and ".I('intro')." = 1";
        
        $cat_id = I('cat_id');
    	if($cat_id){    	    
            $goods_category = M('goods_category')->where("id = $cat_id")->find();
            $where = " $where  and cat_id{$goods_category['level']} = $cat_id "; // 初始化搜索条件
            $this->assign('cat_id',$cat_id);
    	}
        if(I('brand_id')){
            $this->assign('brand_id',I('brand_id'));
            $where = "$where and brand_id = ".I('brand_id');
        }
    	if(!empty($_REQUEST['keywords']))
    	{
    		$this->assign('keywords',I('keywords'));
    		$where = "$where and (goods_name like '%".I('keywords')."%' or keywords like '%".I('keywords')."%')" ;
    	} 

        $count = M('goods')->where($where)->count();
        $Page  = new AjaxPage($count,10); 	
    	$goodsList = M('goods')->where($where)->order('goods_id DESC')->limit($Page->firstRow.','.$Page->listRows)->select();
        foreach($goodsList as $key => $val)
        {
            $spec_goods = M('spec_goods_price')->where("goods_id = {$val['goods_id']}")->select();
            $goodsList[$key]['spec_goods'] = $spec_goods;            
        }
        
        $store_bind_class = M('store_bind_class')->where("store_id =".STORE_ID)->select();
        $cat_id1 = get_arr_column($store_bind_class, 'class_1');
        $cat_id2 = get_arr_column($store_bind_class, 'class_2');
        $cat_id3 = get_arr_column($store_bind_class, 'class_3');
        $cat_id0 = array_merge($cat_id1,$cat_id2,$cat_id3);
         $show = $Page->show();
        $this->assign('cat_id0',$cat_id0);
    	$this->assign('goodsList',$goodsList);
         $this->assign('page',$show);// 赋值分页输出
    	$this->display();        
    }
    
    public function ajaxOrderNotice(){
        $order_amount = M('order')->where(array('order_status'=>0))->count();
        echo $order_amount;
    }
    public function fahuo(){
        $order_id = I('order_id');
        $orderLogic = new OrderLogic();
        $order = $orderLogic->getOrderInfo($order_id);
        $orderGoods = $orderLogic->getOrderGoods($order_id);
        $delivery_record = M('delivery_doc')->join('LEFT JOIN __SELLER__ ON __SELLER__.seller_id = __DELIVERY_DOC__.admin_id')->where('order_id='.$order_id)->select();
        if($delivery_record){
            $order['invoice_no'] = $delivery_record[count($delivery_record)-1]['invoice_no'];
        }
        $this->assign('order',$order);
        $this->assign('orderGoods',$orderGoods);
        $this->assign('delivery_record',$delivery_record);//发货记录
        $this->display();
    }
    public function fahuo_add(){
        $order_id=$_POST['order_id'];   
        $shipping_status=$_POST['shipping_status'];
        $order=M('order')->where("order_id=$order_id")->save(array('shipping_status'=>$shipping_status));
        if($order){
            $this->success('操作成功',U('Order/index'));
        }else{
            $this->success('操作失败',U('Order/index'));
        }
    }
      public function fayao_print(){
        $order_id = I('order_id');
        $orderLogic = new OrderLogic();
        $order = $orderLogic->getOrderInfo($order_id);
        $orderGoods = $orderLogic->getOrderGoods($order_id);
        $this->assign('order',$order);
        $this->assign('orderGoods',$orderGoods);
        $this->display();
    }



    /**
     * 选择搜索商品
     */
    public function zs_goods()
    {
        $brandList =  M("brand")->select();
        $categoryList =  M("goods_category")->select();
        $this->assign('categoryList',$categoryList);
        $this->assign('brandList',$brandList);      
        $where = ' store_id=0 and  is_on_sale = 1 ';//搜索条件
        I('intro')  && $where = "$where and ".I('intro')." = 1";
        
        $cat_id = I('cat_id');
        if($cat_id){            
            $goods_category = M('goods_category')->where("id = $cat_id")->find();
            $where = " $where  and cat_id{$goods_category['level']} = $cat_id "; // 初始化搜索条件
            $this->assign('cat_id',$cat_id);
        }
        if(I('brand_id')){
            $this->assign('brand_id',I('brand_id'));
            $where = "$where and brand_id = ".I('brand_id');
        }
        if(!empty($_REQUEST['keywords']))
        {
            $this->assign('keywords',I('keywords'));
            $where = "$where and (goods_name like '%".I('keywords')."%' or keywords like '%".I('keywords')."%')" ;
        } 

        $count = M('goods')->where($where)->count();
        $Page  = new AjaxPage($count,10);   
        $goodsList = M('goods')->where($where)->order('goods_id DESC')->limit($Page->firstRow.','.$Page->listRows)->select();
        foreach($goodsList as $key => $val)
        {
            $spec_goods = M('spec_goods_price')->where("goods_id = {$val['goods_id']}")->select();
            $goodsList[$key]['spec_goods'] = $spec_goods;            
        }
        
        $store_bind_class = M('store_bind_class')->where("store_id =".STORE_ID)->select();
        $cat_id1 = get_arr_column($store_bind_class, 'class_1');
        $cat_id2 = get_arr_column($store_bind_class, 'class_2');
        $cat_id3 = get_arr_column($store_bind_class, 'class_3');
        $cat_id0 = array_merge($cat_id1,$cat_id2,$cat_id3);
         $show = $Page->show();
        $this->assign('cat_id0',$cat_id0);
        $this->assign('goodsList',$goodsList);
         $this->assign('page',$show);// 赋值分页输出
        $this->display();        
    }
}
